package utils;

import java.util.Arrays;
import java.util.Comparator;

public class Search {

    public String BinSearch(String[] arr, int target){
        int l = 0, r = arr.length-1;
        if(arr.length <= 1){
            if(arr.length == 1 && arr[0].split(",")[1].substring(1).equals(""+target)){
                return arr[0];
            }
            return null;
        }
        if(arr.length > 1 && !arr[1].isBlank()){
            Arrays.sort(arr, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    // 提取第一个逗号前的数字
                    String[] split1 = o1.split(",");
                    String[] split2 = o2.split(",");

                    // 将字符串转换为整数进行比较
                    int num1 = Integer.parseInt(split1[0].substring(1));
                    int num2 = Integer.parseInt(split2[0].substring(1));

                    return Integer.compare(num1, num2); // 升序排列
                }
            });
        }
        while(l <= r){
            int mid = (l+r)>>1;
            int id = Integer.parseInt(arr[mid].split(",")[0].substring(1));
            if(id > target){
                r = mid-1;
            }
            else if(id < target){
                l = mid+1;
            }
            else{
                return arr[mid];
            }
        }
        return null;
    }
    
}
